package com.itheima.interceptors;

import com.itheima.pojo.Emp;
import com.itheima.utils.JwtUtils;
import com.itheima.utils.TliasThreadLocal;
import io.jsonwebtoken.Claims;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // return HandlerInterceptor.super.preHandle(request, response, handler);
        // System.out.println(" 在进行 资源请求之前 会先执行我:preHandle方法，我来决定是否放行 " );

        // 1,取出token
        String token = request.getHeader("Token");
        // 2,判断token 是否有值
        if(token ==null || " ".equals(token)){
        //     此时说明 token没有值 返回401状态码，并禁止通信
            response.setStatus(401);
            return  false;
        }

        // 3,校验token的有效期
        try {
            Claims claims = JwtUtils.parseJWT(token);

            // TliasThreadLocal.setEmpThreadLocal((Emp)claims);
            TliasThreadLocal.setEmpId(claims.get("id",Integer.class));
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            // throw new RuntimeException(e);
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        System.out.println(" api请求完成后 会再会到拦截器中的 postHandle（）中： " );

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
